package org.port.weather.data;

import org.port.util.Util;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;

public class WeatherCP extends ContentProvider {
	public static final String TAG = "WeatherCP";
	public static final String DB = "myport";
	public static int VER = 1;
	public static final String TABLE_LOCATION = "ocation";
	public static final String TABLE_WEATHER = "weather";
	public static final String ID = "_id";
	public static final String SIDO = "_sido";
	public static final String GUGUN = "_gugun";
	public static final String DONG = "_dong";
	public static final String DATE = "_date";
	public static final String HOUR = "_hour";
	public static final String STATE = "_state";
	public static final String TEMP = "_temp";
	public static final String RAIN = "_rain";
	public static final String SNOW = "_snow";
	public static final String WIND = "_wind";
	public static final String WS = "_ws";
	public static final String WD = "_wd";
	private static final int LOCATION_ALL = 1;
	private static final int LOCATION_ONE = 2;
	private static final int WEATHER_ALL = 3;
	private static final int WEATHER_ONE = 4;
	public static final int LOG_WEATHER = 100;
	public static final int LOG_LOCATION = 200;
	public WeatherDBHelper dbHelper;
	public static final Uri LOCATION_URI = Uri
			.parse("content://org.port.db/location");
	public static final Uri WEATHER_URI = Uri
			.parse("content://org.port.db/weather");
	private SQLiteDatabase database = null;
	static final UriMatcher MATCHER;
	static {
		MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
		MATCHER.addURI("org.port.db", "location", LOCATION_ALL);
		MATCHER.addURI("org.port.db", "location/*", LOCATION_ONE);
		MATCHER.addURI("org.port.db", "weather", WEATHER_ALL);
		MATCHER.addURI("org.port.db", "weather/*", WEATHER_ONE);
	}

	private static final String CREATE_WEATHER = "CREATE TABLE IF NOT EXISTS "
			+ TABLE_WEATHER + " (" + ID
			+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + HOUR + " TEXT, " + DATE
			+ " TEXT, " + STATE + " TEXT, " + TEMP + " TEXT, " + RAIN
			+ " TEXT, " + SNOW + " TEXT, " + WIND + " TEXT, " + WD + " TEXT, "
			+ WS + " TEXT" + ")";

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		// TODO Auto-generated method stub
		int cnt = 0;
		switch (MATCHER.match(uri)) {
		case WEATHER_ALL:
			cnt = database.delete(TABLE_WEATHER, selection, selectionArgs);
			break;
		case WEATHER_ONE:
			cnt = database.delete(TABLE_WEATHER, selection, selectionArgs);
			break;

		default:
			break;
		}
		getContext().getContentResolver().notifyChange(uri, null);
		return cnt;
	}

	@Override
	public String getType(Uri uri) {
		// TODO Auto-generated method stub
		switch (MATCHER.match(uri)) {
		case WEATHER_ALL:
			return "vnd.org.port.db.WeatherCP.dir//contacts";
		case WEATHER_ONE:
			return "vnd.org.port.db.WeatherCP.item//contacts";
		default:
			throw new IllegalArgumentException(TAG + " Unsupport URI: " + uri);
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		// TODO Auto-generated method stub
		Uri tUri = null;
		switch (MATCHER.match(uri)) {
		case WEATHER_ALL:
			long wId = database.insert(TABLE_WEATHER, "", values);
			if (wId > 0) {
				tUri = ContentUris.withAppendedId(WEATHER_URI, wId);
				getContext().getContentResolver().notifyChange(tUri, null);
			} else {
				try {
					throw new SQLException("Fail to add new item into " + uri);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			break;
		case WEATHER_ONE:

			break;

		default:
			break;
		}
		return null;
	}

	/**
	 * Create DBHelper & SQLiteDatabase Class, DB_VER get SharedPreferences
	 */
	@Override
	public boolean onCreate() {
		// TODO Auto-generated method stub
		dbHelper = new WeatherDBHelper(getContext(), DB, null, Util.getPrefer(
				getContext()).getInt(Util.DB_VER, VER));
		database = dbHelper.getWritableDatabase();
		return (database == null) ? false : true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		// TODO Auto-generated method stub
		SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
		switch (MATCHER.match(uri)) {
		case WEATHER_ALL:
			builder.setTables(TABLE_WEATHER);
			break;
		case WEATHER_ONE:
			builder.setTables(TABLE_WEATHER);
			break;

		default:
			break;
		}
		Cursor c = builder.query(database, projection, selection,
				selectionArgs, null, null, sortOrder);
		c.setNotificationUri(getContext().getContentResolver(), uri);
		return c;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		// TODO Auto-generated method stub
		int cnt = 0;
		try {
			switch (MATCHER.match(uri)) {
			case WEATHER_ALL:
				cnt = database.update(TABLE_WEATHER, values, selection,
						selectionArgs);
				break;
			case WEATHER_ONE:
				cnt = database.update(TABLE_WEATHER, values, selection,
						selectionArgs);
				break;

			default:
				break;
			}

		} catch (SQLiteException e) {
			// TODO: handle exception
			VER = Util.getPrefer(getContext()).getInt(Util.DB_VER, VER);
			if (dbHelper != null) {
				dbHelper.onUpgrade(database, VER, VER + 1);
			} else {
				dbHelper = new WeatherDBHelper(getContext(), DB, null, VER);
				dbHelper.onUpgrade(database, VER, VER + 1);
			}
		}
		return cnt;
	}

	public static class WeatherDBHelper extends SQLiteOpenHelper {
		Context context;

		public WeatherDBHelper(Context context, String name,
				CursorFactory factory, int version) {
			super(context, name, factory, version);
			// TODO Auto-generated constructor stub
			this.context = context;
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			// TODO Auto-generated method stub
			db.execSQL(CREATE_WEATHER);
			ContentValues cv = new ContentValues();

			for (int i = 0; i < 3; i++) {
				int h = 3;
				for (int j = 0; j < 8; j++) {
					cv.clear();
					cv.put(DATE, Integer.toString(i));
					cv.put(HOUR, Integer.toString(h));
					db.insert(TABLE_WEATHER, null, cv);
					h += 3;
				}
			}
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO Auto-generated method stub
			Util.getPreferEditor(context).putInt(Util.DB_VER, newVersion);
			db.execSQL("DROP TABLE IF EXISTS " + TABLE_WEATHER);
			onCreate(db);
		}
	}
}
